<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width,initial-scale=1"><title>JVM-垃圾回收 | yili的个人小站</title><meta name="keywords" content="JVM"><meta name="author" content="yili"><meta name="copyright" content="yili"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="垃圾回收对象已死两种回收策略1.引用计数器法如果一个地方进行引用则会加一，一个地方的引用取消则会减一。 注意：如果出现相互引用的情况，则会出现这两个引用都不会被垃圾回收 123456789101112public class StringDemo &amp;#123;    public StringDemo instance &#x3D; null;        public static void main(">
<meta property="og:type" content="article">
<meta property="og:title" content="JVM-垃圾回收">
<meta property="og:url" content="https://yili979.gitee.io/blog/2021/10/05/jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/index.html">
<meta property="og:site_name" content="yili的个人小站">
<meta property="og:description" content="垃圾回收对象已死两种回收策略1.引用计数器法如果一个地方进行引用则会加一，一个地方的引用取消则会减一。 注意：如果出现相互引用的情况，则会出现这两个引用都不会被垃圾回收 123456789101112public class StringDemo &amp;#123;    public StringDemo instance &#x3D; null;        public static void main(">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/10/06/nNuTKYH48X3mvLo.png">
<meta property="article:published_time" content="2021-10-04T16:16:56.000Z">
<meta property="article:modified_time" content="2021-10-06T15:35:34.851Z">
<meta property="article:author" content="yili">
<meta property="article:tag" content="JVM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/10/06/nNuTKYH48X3mvLo.png"><link rel="shortcut icon" href="/blog/img/favicon.ico"><link rel="canonical" href="https://yili979.gitee.io/blog/2021/10/05/jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#121212","position":"bottom-left"},
  source: {
    jQuery: 'https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js',
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/js/jquery.justifiedGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/justifiedGallery/dist/css/justifiedGallery.min.css'
    },
    fancybox: {
      js: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js',
      css: 'https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isanchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'JVM-垃圾回收',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2021-10-06 23:35:34'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const fontSizeVal = saveToLocal.get('global-font-size')
    if (fontSizeVal !== undefined) {
      document.documentElement.style.setProperty('--global-font-size', fontSizeVal + 'px')
    }
    
    const detectApple = () => {
      if (GLOBAL_CONFIG_SITE.isHome && /iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><link rel="stylesheet" href="/blog/css/custom.css" media="defer" onload="this.media='all'"><meta name="generator" content="Hexo 5.4.0"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/10/05/BKpC6sFEo5Dl7qA.jpg" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data"><div class="data-item is-center"><div class="data-item-link"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">28</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div></div><div class="data-item is-center"><div class="data-item-link"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://i.loli.net/2021/10/06/nNuTKYH48X3mvLo.png')"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">yili的个人小站</a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/blog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/blog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">JVM-垃圾回收</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2021-10-04T16:16:56.000Z" title="发表于 2021-10-05 00:16:56">2021-10-05</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2021-10-06T15:35:34.851Z" title="更新于 2021-10-06 23:35:34">2021-10-06</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/JVM/">JVM</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.1k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="JVM-垃圾回收"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h1 id="垃圾回收"><a href="#垃圾回收" class="headerlink" title="垃圾回收"></a>垃圾回收</h1><h3 id="对象已死"><a href="#对象已死" class="headerlink" title="对象已死"></a>对象已死</h3><h4 id="两种回收策略"><a href="#两种回收策略" class="headerlink" title="两种回收策略"></a>两种回收策略</h4><h5 id="1-引用计数器法"><a href="#1-引用计数器法" class="headerlink" title="1.引用计数器法"></a>1.引用计数器法</h5><p>如果一个地方进行引用则会加一，一个地方的引用取消则会减一。</p>
<p>注意：如果出现相互引用的情况，则会出现这两个引用都不会被垃圾回收</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StringDemo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">public</span> StringDemo instance = <span class="keyword">null</span>;</span><br><span class="line">    </span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        StringDemo stringDemo1 = <span class="keyword">new</span> StringDemo();</span><br><span class="line">        StringDemo stringDemo2 = <span class="keyword">new</span> StringDemo();</span><br><span class="line">        stringDemo1.instance = stringDemo2;</span><br><span class="line">        stringDemo2.instance = stringDemo1;</span><br><span class="line">        stringDemo1 = <span class="keyword">null</span>;</span><br><span class="line">        stringDemo2 = <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h5 id="2-可达性分析算法"><a href="#2-可达性分析算法" class="headerlink" title="2.可达性分析算法"></a>2.可达性分析算法</h5><p><img src="https://i.loli.net/2021/10/05/ORwHsDYUvp2ILSz.png" alt="可达性分析算法的操作图"></p>
<p>在java技术中，可固定被作为GC root 的有如下几种：</p>
<ol>
<li>虚拟机栈中引用的对象</li>
<li>类方法所引用的对象</li>
<li>常量所引用的对象</li>
<li>本地native方法所引用的对象</li>
<li>synchronized所持有的对象</li>
</ol>
<h4 id="引用类型"><a href="#引用类型" class="headerlink" title="引用类型"></a>引用类型</h4><ol>
<li><p>强引用</p>
<p>强引用就是虚拟机栈的直接引用，除非引用指向消失，否则堆出现OOM也不会将强引用进行消除</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StringDemo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">int</span> i = <span class="number">2</span>;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        StringDemo stringDemo1 = <span class="keyword">new</span> StringDemo();</span><br><span class="line">        StringDemo stringDemo2 = <span class="keyword">new</span> StringDemo();</span><br><span class="line">        stringDemo2 = <span class="keyword">null</span>;</span><br><span class="line">        System.gc();</span><br><span class="line">        System.out.println(stringDemo1);</span><br><span class="line">        System.out.println(stringDemo2);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//com.yili.interview.StringDemo@14ae5a5</span></span><br><span class="line"><span class="comment">//null</span></span><br></pre></td></tr></table></figure></li>
<li><p>软引用</p>
<p>软引用会在虚拟机内存空间不足的时候对内存进行清理</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">package</span> com.yili.interview;</span><br><span class="line"></span><br><span class="line"><span class="keyword">import</span> java.lang.ref.SoftReference;</span><br><span class="line"><span class="keyword">import</span> java.util.ArrayList;</span><br><span class="line"><span class="keyword">import</span> java.util.List;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">StringDemo</span> </span>&#123;</span><br><span class="line">    <span class="keyword">private</span> <span class="keyword">static</span> List&lt;Object&gt; list = <span class="keyword">new</span> ArrayList&lt;&gt;();</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        testSoftReference();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">testSoftReference</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">byte</span>[] buff = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; i &lt; <span class="number">10</span>; i++) &#123;</span><br><span class="line">            buff = <span class="keyword">new</span> <span class="keyword">byte</span>[<span class="number">1024</span> * <span class="number">1024</span>];</span><br><span class="line">            SoftReference&lt;<span class="keyword">byte</span>[]&gt; sr = <span class="keyword">new</span> SoftReference&lt;&gt;(buff);</span><br><span class="line">            list.add(sr);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.gc(); <span class="comment">//主动通知垃圾回收</span></span><br><span class="line"></span><br><span class="line">        <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span>; i &lt; list.size(); i++)&#123;</span><br><span class="line">            Object obj = ((SoftReference) list.get(i)).get();</span><br><span class="line">            System.out.println(obj);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        System.out.println(<span class="string">&quot;buff: &quot;</span> + buff.toString());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//null</span></span><br><span class="line"><span class="comment">//[B@14ae5a5</span></span><br><span class="line"><span class="comment">//[B@7f31245a</span></span><br><span class="line"><span class="comment">//buff: [B@7f31245a</span></span><br></pre></td></tr></table></figure></li>
<li><p>弱引用</p>
<p>弱引用是jvm虚拟机只要执行gc程序就一定会对其进行回收的引用</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> java.lang.ref.WeakReference;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WeakReferenceTest</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">static</span> <span class="keyword">void</span> <span class="title">main</span><span class="params">(String[] args)</span> </span>&#123;</span><br><span class="line">        Object o = <span class="keyword">new</span> Object();</span><br><span class="line">        WeakReference&lt;Object&gt; reference = <span class="keyword">new</span> WeakReference&lt;Object&gt;(o);</span><br><span class="line">        o = <span class="keyword">null</span>;</span><br><span class="line">        System.gc();</span><br><span class="line">        System.out.println(reference.get());</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//null</span></span><br></pre></td></tr></table></figure></li>
<li><p>虚引用</p>
<p>虚引用和没有引用一样，随时可能会被jvm程序进行回收</p>
<blockquote>
<p>虚引用也称为“幽灵引用”或者“幻影引用”，它是最弱的一种引用关系。一个对象是否有虚引用的 存在，完全不会对其生存时间构成影响，也无法通过虚引用来取得一个对象实例。为一个对象设置虚 引用关联的唯一目的只是为了能在这个对象被收集器回收时收到一个系统通知。</p>
</blockquote>
</li>
</ol>
<h4 id="对象的自我拯救"><a href="#对象的自我拯救" class="headerlink" title="对象的自我拯救"></a>对象的自我拯救</h4><p>如果一个对象被gc判定为一个要进行处理的对象，也不一定是非死不可。</p>
<p>要判定一个对象死亡，至少要经历两轮标记过程：首先进行一次可达性分析，如果没有达到GC root，进行第二次筛选，判断一个对象有没有自己的finalize()方法可以进行执行，或者finalize方法有没有执行过finalize方法，这两种情况被判定为没有必要执行finalize方法，直接将对象进行销毁</p>
<p>如果要执行finalize方法，则先将这个对象添加到一个名为F-Queue的队列中，然后通过一个低调度的线程对这个方法进行执行。</p>
<h4 id="回收方法区"><a href="#回收方法区" class="headerlink" title="回收方法区"></a>回收方法区</h4><p>回收方法区需要具备以下的特性：</p>
<ul>
<li>该类的所有实例变量都被回收</li>
<li>加载这个类的类加载器已经消亡</li>
<li>该类所生成的java.lang.Class对象没有在别的地方被引用</li>
</ul>
<p>注意：一般情况下，方法区内的数据不会被回收，（类加载器，如果不是被精心设计的类加载器，这个条件很难被达成）</p>
<h3 id="垃圾回收算法"><a href="#垃圾回收算法" class="headerlink" title="垃圾回收算法"></a>垃圾回收算法</h3><h4 id="分代收集理论"><a href="#分代收集理论" class="headerlink" title="分代收集理论"></a>分代收集理论</h4><p>现今存在的垃圾收集器，大多都遵循着“分代收集（Generational Collection）”。</p>
<p>1）弱分代假说（Weak Generational Hypothesis) : 绝大多数对象都是朝生夕灭的。</p>
<p>2）强分代假说（Strong Generational Hypothesis) : 熬过多次垃圾收集过程的对象就比较难进行清除。</p>
<p>通过上述的俩个假说，基本奠定了现在的垃圾处理器的一致设计原则：收集器会在堆中划分出不同的区域，然后根据对象存在的时间划分到不同的区域中进行存储。</p>
<p>在划分不同的区域中后，垃圾回收器会通过区域来进行收集，每次只清理某一个或者某一个分区的内存即可。</p>
<p><strong>由于新生代中可能会存在老年代的引用，所以在进行分析时，会遍历老年代的所有对象进行查找，会十分占用时间，所以得到了第三个假说</strong></p>
<p>3）跨代引用假说（Intergenerational Reference Hypothesis）：跨代引用相对于同代引用只占少数</p>
<p>依据这条假说，我们就不应再为了少量的跨代引用去扫描整个老年代，也不必浪费空间专门记录 每一个对象是否存在及存在哪些跨代引用，只需在新生代上建立一个全局的数据结构（该结构被称 为“记忆集”，Remembered Set），这个结构把老年代划分成若干小块，标识出老年代的哪一块内存会存在跨代引用。此后当发生Minor GC时，只有包含了跨代引用的小块内存里的对象才会被加入到GC Roots进行扫描。虽然这种方法需要在对象改变引用关系（如将自己或者某个属性赋值）时维护记录数 据的正确性，会增加一些运行时的开销，但比起收集时扫描整个老年代来说仍然是划算的。</p>
<h4 id="标记-清除算法"><a href="#标记-清除算法" class="headerlink" title="标记-清除算法"></a>标记-清除算法</h4><p>标记-清除算法（Mark-Sweep）</p>
<p>首先对不进行清除的对象进行标记，然后清除剩下的对象</p>
<p>基本上后续的收集算法都是通过标记-清除算法演化而来的。其缺点主要有两个：第一个是执行不稳定，第二个是内存空间零碎化的问题，由于剩余的内存太过零碎，导致后来进行内存分配时，无法给新内存分配足够的内存空间，导致不得不提前进行一次垃圾回收工作。</p>
<h4 id="标记-复制算法"><a href="#标记-复制算法" class="headerlink" title="标记-复制算法"></a>标记-复制算法</h4><p>标记-复制算法是现在大多数虚拟机所采用的一种垃圾回收算法。</p>
<p>最开始的构想是通过设置两个1：1的区域进行分配，然后标记不需要进行清除的算法复制到右边区域中，然后将另一块区域中的空间进行清除。</p>
<p><strong>但是新生代中98%的对象都会熬不过第一轮收集</strong></p>
<blockquote>
<p>标记-复制算法在对象存活率较高时就要进行较多的复制操作，效率将会降低。更关键的是，如果 不想浪费50%的空间，就需要有额外的空间进行分配担保，以应对被使用的内存中所有对象都100%存 活的极端情况，所以在老年代一般不能直接选用这种算法！</p>
</blockquote>
<h4 id="标记-整理算法"><a href="#标记-整理算法" class="headerlink" title="标记-整理算法"></a>标记-整理算法</h4><p>标记-整理算法是针对老年代的存亡特性所设计的一种收集算法，标记不需要进行回收的对象，然后将对象进行移动到连续的空间中，以便于剩下的对象进入。</p>
<p>标记-清除算法与标记-整理算法的本质差异在于前者是一种非移动式的回收算法，而后者是移动 式的。是否移动回收后的存活对象是一项优缺点并存的风险决策：</p>
<ul>
<li>如果将对象进行移动，在老年区这种每次都有很多对象存活的区域，更新引用的过程会十分麻烦，并且移动的过程是会暂停所有应用活动，被称之为“Stop the world”</li>
<li>但是如果不进行移动的化，则会出现过多的内存碎片，只能依靠更为复杂的内存分配器和内存访问器来解决，</li>
</ul>
<p>所以这两种情况都存在弊端：</p>
<p>移动时内存回收会更复杂，不移动则内存分配会更复杂。依据分析，移动则吞吐量更高，不移动则内存响应速度会更快。</p>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">yili</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://yili979.gitee.io/blog/2021/10/05/jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/">https://yili979.gitee.io/blog/2021/10/05/jvm/JVM-%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://yili979.gitee.io/blog" target="_blank">yili的个人小站</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/JVM/">JVM</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/10/06/nNuTKYH48X3mvLo.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/social-share.js/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/social-share.js/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2021/10/05/jvm/JVM-%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/"><img class="prev-cover" src="https://i.loli.net/2018/11/05/5bdfce578c055.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">JVM-内存区域</div></div></a></div><div class="next-post pull-right"><a href="/blog/2021/10/05/jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B/"><img class="next-cover" src="https://i.loli.net/2021/10/05/Lf36O8MDvnZux2A.png" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">JVM-类加载过程</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2021/10/05/jvm/JVM-%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/" title="JVM-内存区域"><img class="cover" src="https://i.loli.net/2018/11/05/5bdfce578c055.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-10-05</div><div class="title">JVM-内存区域</div></div></a></div><div><a href="/blog/2021/10/05/jvm/JVM-%E7%B1%BB%E5%8A%A0%E8%BD%BD%E8%BF%87%E7%A8%8B/" title="JVM-类加载过程"><img class="cover" src="https://i.loli.net/2021/10/05/Lf36O8MDvnZux2A.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2021-10-05</div><div class="title">JVM-类加载过程</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/10/05/BKpC6sFEo5Dl7qA.jpg" onerror="this.onerror=null;this.src='/blog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">yili</div><div class="author-info__description">身骑白马</div></div><div class="card-info-data"><div class="card-info-data-item is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">28</div></a></div><div class="card-info-data-item is-center"><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a></div><div class="card-info-data-item is-center"><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">13</div></a></div></div><a class="button--animated" id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/qiuyuyin"><i class="fab fa-github"></i><span>github🍟</span></a></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn card-announcement-animation"></i><span>公告</span></div><div class="announcement_content">啦啦啦，写的不好还请见谅😉<div class="twopeople"><div class="twopeople"><div class="container"style="height:200px;"><canvas class="illo"width="800"height="800"style="max-width: 200px; max-height: 200px; touch-action: none; width: 640px; height: 640px;"></canvas></div><script src="js/twopeople1.js"></script><script src="js/zdog.dist.js"></script><script id="rendered-js"src="js/twopeople.js"></script><style>.twopeople{margin:0;align-items:center;justify-content:center;text-align:center}canvas{display:block;margin:0 auto;cursor:move}</style></div></div></div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6"><span class="toc-text">垃圾回收</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E5%B7%B2%E6%AD%BB"><span class="toc-text">对象已死</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E4%B8%A4%E7%A7%8D%E5%9B%9E%E6%94%B6%E7%AD%96%E7%95%A5"><span class="toc-text">两种回收策略</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E5%BC%95%E7%94%A8%E8%AE%A1%E6%95%B0%E5%99%A8%E6%B3%95"><span class="toc-text">1.引用计数器法</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2-%E5%8F%AF%E8%BE%BE%E6%80%A7%E5%88%86%E6%9E%90%E7%AE%97%E6%B3%95"><span class="toc-text">2.可达性分析算法</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%BC%95%E7%94%A8%E7%B1%BB%E5%9E%8B"><span class="toc-text">引用类型</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AF%B9%E8%B1%A1%E7%9A%84%E8%87%AA%E6%88%91%E6%8B%AF%E6%95%91"><span class="toc-text">对象的自我拯救</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%9B%9E%E6%94%B6%E6%96%B9%E6%B3%95%E5%8C%BA"><span class="toc-text">回收方法区</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6%E7%AE%97%E6%B3%95"><span class="toc-text">垃圾回收算法</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%88%86%E4%BB%A3%E6%94%B6%E9%9B%86%E7%90%86%E8%AE%BA"><span class="toc-text">分代收集理论</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A0%87%E8%AE%B0-%E6%B8%85%E9%99%A4%E7%AE%97%E6%B3%95"><span class="toc-text">标记-清除算法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A0%87%E8%AE%B0-%E5%A4%8D%E5%88%B6%E7%AE%97%E6%B3%95"><span class="toc-text">标记-复制算法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#%E6%A0%87%E8%AE%B0-%E6%95%B4%E7%90%86%E7%AE%97%E6%B3%95"><span class="toc-text">标记-整理算法</span></a></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/something-about-crypto/" title="something about crypto"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/image-20220124000713258.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="something about crypto"/></a><div class="content"><a class="title" href="/blog/2022/03/08/something-about-crypto/" title="something about crypto">something about crypto</a><time datetime="2022-03-08T12:01:13.000Z" title="发表于 2022-03-08 20:01:13">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/golang%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="golang内存管理"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/202203081958270.png" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="golang内存管理"/></a><div class="content"><a class="title" href="/blog/2022/03/08/golang%E5%86%85%E5%AD%98%E7%AE%A1%E7%90%86/" title="golang内存管理">golang内存管理</a><time datetime="2022-03-08T11:55:30.000Z" title="发表于 2022-03-08 19:55:30">2022-03-08</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/blog/2022/03/08/%E9%89%B4%E6%9D%83%E7%B3%BB%E7%BB%9F/" title="鉴权系统"><img src="https://yili979.oss-cn-beijing.aliyuncs.com/img/202203081950401.jpeg" onerror="this.onerror=null;this.src='/blog/img/404.jpg'" alt="鉴权系统"/></a><div class="content"><a class="title" href="/blog/2022/03/08/%E9%89%B4%E6%9D%83%E7%B3%BB%E7%BB%9F/" title="鉴权系统">鉴权系统</a><time datetime="2022-03-08T11:49:53.000Z" title="发表于 2022-03-08 19:49:53">2022-03-08</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2022 By yili</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="font-plus" type="button" title="放大字体"><i class="fas fa-plus"></i></button><button id="font-minus" type="button" title="缩小字体"><i class="fas fa-minus"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="false" src="https://cdn.jsdelivr.net/npm/butterfly-extsrc@1/dist/canvas-fluttering-ribbon.min.js"></script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>